package cn.catsdad.service.impl;

import cn.catsdad.base.page.PageBean;
import cn.catsdad.base.page.PageParam;
import cn.catsdad.base.service.impl.BaseCrudServiceImpl;
import cn.catsdad.dto.DictDetailDTO;
import cn.catsdad.entity.DictDetail;
import cn.catsdad.repository.DictDetailRepository;
import cn.catsdad.service.api.DictDetailService;
import cn.catsdad.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 常量明细service实现
 *
 * @author xuyonglong
 * @version V1.0 2023/4/24
 */
@Service
public class DictDetailServiceImpl extends BaseCrudServiceImpl<DictDetailDTO, Long, DictDetailRepository> implements DictDetailService {

    @Override
    public void pageQuery(PageBean<DictDetailDTO> page, PageParam param) {
        page.setEntityName("DtoDictDetail d").setQuery("select d");
        super.pageQuery(page, param);
    }

    @Override
    public Map<Long, List<DictDetailDTO>> queryDetailByDictIds(Collection<Long> dictIds) {
        Map<Long, List<DictDetailDTO>> result = new HashMap<>(dictIds.size());
        if (StringUtil.isNotEmpty(dictIds)) {
            result = repository.findByDictIdInAndIsDeletedFalse(dictIds).stream().collect(Collectors.groupingBy(DictDetail::getDictId));
        }
        return result;
    }

    @Override
    public List<DictDetailDTO> queryByDictIdAndIsDeletedFalse(Long dictId) {
        List<DictDetailDTO> result = new ArrayList<>();
        if (dictId != null) {
            result = repository.findByDictIdInAndIsDeletedFalse(Collections.singleton(dictId));
        }
        return result;
    }

    /**
     * 根据字典id查询
     *
     * @param dictIds 字典id集合
     * @return 详情
     */
    @Override
    public List<DictDetailDTO> queryByDictIds(Collection<Long> dictIds) {
        List<DictDetailDTO> result = new ArrayList<>();
        if (StringUtil.isNotEmpty(dictIds)) {
            result = repository.findByDictIdInAndIsDeletedFalse(dictIds);
        }
        return result;
    }

    @Override
    @Transactional
    public void deleteByDictIds(Collection<Long> dictIds) {
        if (StringUtil.isNotEmpty(dictIds)) {
            List<DictDetailDTO> details = repository.findByDictIdInAndIsDeletedFalse(dictIds);
            if (StringUtil.isNotEmpty(details)) {
                logicDeleteByIds(details.stream().map(DictDetailDTO::getId).collect(Collectors.toList()));
            }
        }
    }
}
